package cn.yunbamboos.listener;

import cn.yunbamboos.db.DB;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import java.time.Duration;

public class YunbamboosSpringApplicationRunListener implements SpringApplicationRunListener {

    private static final Logger logger = LoggerFactory.getLogger(YunbamboosSpringApplicationRunListener.class);

    /**
     * run方法刚开始时就调用，用于非常早期的初始化
     * */
    @Override
    public void starting(ConfigurableBootstrapContext bootstrapContext) {
        logger.debug("starting");
    }

    /**
     * env准备好后，context创建之前调用
     * */
    @Override
    public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
        environment.getSystemEnvironment();
    }

    /**
     * context创建好但是source(bean)还没有加载
     * */
    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        String modelPackageName = context.getEnvironment().getProperty("yunbamboos.model-package-name");
        DB.check(modelPackageName);
    }

    /**
     * context加载完但是还没有refresh
     * */
    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        logger.debug("contextLoaded");
    }

    /**
     * context已经refreshed并且application已经启动，org.springframework.boot.CommandLineRunner和org.springframework.boot.ApplicationRunner还未调用
     * */
    @Override
    public void started(ConfigurableApplicationContext context, Duration timeTaken) {
        logger.debug("started");
    }

    @Override
    public void ready(ConfigurableApplicationContext context, Duration timeTaken) {
        logger.debug("ready");
    }

    /**
     * application运行失败时
     * */
    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        logger.error("failed", exception);
    }
}
